import { userAtuthModel } from './user_auth.model';
import { connection } from '../app/database/mysql';

/**
 * 创建
 */
export const createUserAuth = async (post: userAtuthModel) => {
  // 准备查询
  const statement = `
    INSERT INTO user_auth
    SET ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, post);

  // 提供数据
  return data;
};

/**
 * 查询权限
 */
export const selectUserAuth = async (user_id: number) => {
  // 准备查询
  const statement = `
    SELECT * FROM user_auth
    WHERE user_id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, user_id);

  // 提供数据
  return data;
};

/**
 * 减去发布权限
 */
export const reduceSendAuth = async (user_id: number) => {
  // 准备查询
  const statement = `
    UPDATE user_auth SET
    send_info_count=send_info_count -1
    WHERE user_id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, user_id);

  // 提供数据
  return data;
}

/**
 * 更新
 */
export const userAuthUpdate = async (user_id: number, post: userAtuthModel) => {
  // 准备查询
  const statement = `
    UPDATE user_auth
    SET ?
    WHERE user_id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, [post, user_id]);

  // 提供数据
  return data;
}

/**
 * 查询礼包(签到)
 */
export const selectUseSignLibaorAuth = async (user_id: number) => {
  // 准备查询
  const statement = `
    SELECT * FROM user_sign_libao
    WHERE user_id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, user_id);

  // 提供数据
  return data;
};

/**
 * 添加礼包(签到)
 */
export const createUserSignLibaoAuth = async (post: userAtuthModel) => {
  // 准备查询
  const statement = `
    INSERT INTO user_sign_libao
    SET ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, post);

  // 提供数据
  return data;
};

/**
 * 获取用户 VIP 天数
 */
export const getUserVipDay = async (user_id: number) => {
  const data = await selectUserAuth(user_id);
  let vipTime = '0';

  if (data[0]) {
    let endTime = data[0].endTime;
    let newTime = Math.floor(new Date().getTime() / 1);
    if (newTime > endTime) {
      vipTime = '0';
    } else {
      vipTime = `${Math.ceil((endTime - newTime) / 86400000)}`;
    }
  }

  let res = { name: '会员剩余时间', vipTime: vipTime };

  // 提供数据
  return res;
}
